package com.amado.course42Nio.demo1;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 10:29
 */
public class HttpServerDemo {
    // 两个常量
    private static final String CRLF = "\r\n";
    private static final String BLANK = " ";

    public static void main(String[] args) throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        channel.configureBlocking(false);
        channel.bind(new InetSocketAddress(80));
        channel.register(selector, SelectionKey.OP_ACCEPT);
        //堵塞的io
        while(selector.select()>0){
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if(selectionKey.isAcceptable()){
                    ServerSocketChannel channel1 = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = channel1.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_WRITE);
                    System.out.println("accept");
                }else if(selectionKey.isWritable()){
                    System.out.println("write");
                    SocketChannel channel1 = (SocketChannel) selectionKey.channel();
                    StringBuffer sb = new StringBuffer();
                    sb.append("HTTP/1.1").append(BLANK).append(520).append(BLANK).append("love").append(CRLF);
                    sb.append("Server:v  Server/12.19.06.14").append(CRLF).append("Date:").append(new Date()).append(CRLF);
                    sb.append("Content-type:text/html").append(CRLF);
                    String content = "<html>hello</html>";
                    sb.append("Connection:keep-alive").append(CRLF);
                    sb.append("Content-Length:").append(content.length()).append(CRLF).append(CRLF);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    byteBuffer.put(sb.toString().getBytes());
                    byteBuffer.put(content.getBytes());
                    System.out.println("读取成功！==>" + content);
                    channel1.write(byteBuffer);
                    channel1.close();
                }
            }
        }
    }
}
